from flask import Blueprint, render_template, request, session, redirect, url_for
from .db import get_db
auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['GET'])
def login():
    return render_template('auth/login.html')

@auth_bp.route('/login', methods=['POST'])
def check():
    username = request.form['username']
    password = request.form['password']
    user = get_db().execute('SELECT * FROM user WHERE username = ?', (username,)).fetchone()
    if user is None or password != user['password']:
        return render_template('auth/login.html', error='用户名或密码错误，请重试', username=username, password=password)
    session['username'] = username
    return redirect(url_for('index.index'))

@auth_bp.route('/logout', methods=['GET'])
def logout():
    session.pop('username', None)
    return render_template('auth/login.html')
